package com.hckjsec.oa.filters;

import com.alibaba.fastjson.JSON;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.core.redis.RedisCache;
import com.hckjsec.common.filter.ChangeHttpServletRequestWrapper;
import com.hckjsec.common.filter.RepeatedlyRequestWrapper;
import com.hckjsec.common.utils.ComUtil;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.oa.domain.OaView.AppUserView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebFilter(filterName = "oaFilter",urlPatterns = {"/oa/api/*"})
public class OaFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(OaFilter.class);
    @Autowired
    private RedisCache redisCache;
    @Override
    public void doFilter(ServletRequest rquest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean flag=true;
        ChangeHttpServletRequestWrapper hcReq = new ChangeHttpServletRequestWrapper((HttpServletRequest)rquest);
        String  requestPath = hcReq.getRequestURI();
        requestPath = requestPath.substring(requestPath.lastIndexOf("/")+1).trim();
        if (!"login".equals(requestPath)){
            String headerToken = StringUtils.isHcNull(hcReq.getHeader("token"),"");
            if ("".equals(headerToken)){
                flag=false;
                returnJson((HttpServletResponse)response, AjaxResult.cloud_602("token不能为空"));
            }else {
                AppUserView appUserView = redisCache.getCacheObject(ComUtil.getOaCacheKey(headerToken));
                if (StringUtils.isNull(appUserView)) {
                    flag = false;
                    returnJson((HttpServletResponse) response, AjaxResult.cloud_602("登录已失效，请重新登录"));
                }else{
                    hcReq.addParameter("token", headerToken);
                }
            }
        }else{
            String headerDeviceId = StringUtils.isHcNull(hcReq.getHeader("deviceId"),"");
            if ("".equals(headerDeviceId)){
                flag=false;
                returnJson((HttpServletResponse)response, AjaxResult.cloud_602("设备ID获取失败"));
            }else{
                hcReq.addParameter("deviceId", headerDeviceId);
            }
        }
        if (flag) {
            ServletRequest requestWrapper = null;
            if (rquest instanceof HttpServletRequest && StringUtils.equalsAnyIgnoreCase(rquest.getContentType(),
                    MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE)) {
                requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) hcReq, response);
            }
            System.out.println("进入OA过滤器=======" + ((RepeatedlyRequestWrapper) requestWrapper).getRequestURI());
            if (null == requestWrapper) {
                chain.doFilter(rquest, response);
            } else {
                chain.doFilter(requestWrapper, response);
            }
        }
    }


    private void returnJson(HttpServletResponse response, AjaxResult ajaxResult){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(ajaxResult));
        } catch (IOException e) {
            log.error("请求失败", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
